import cv2

"""定位文本中心点"""
def locate_text_center(
    target_text: str, 
    text_list: list, 
    coord_list: list, 
    partial_match: bool = False
) -> list:
    """
    定位文本中心点
    
    :param target_text: 目标文本
    :param text_list: 文本列表
    :param coord_list: 坐标列表
    :param partial_match: 是否部分匹配
    :return: 中心点坐标列表
    """
    if not text_list or not coord_list or len(text_list) != len(coord_list):
        raise ValueError("文本列表与坐标列表长度不匹配或为空")
    
    # 查找目标文本索引
    indices = []
    for i, text in enumerate(text_list):
        if (partial_match and target_text in text) or (text == target_text):
            indices.append(i)
    
    # 计算中心点坐标
    centers = []
    for idx in indices:
        bbox = coord_list[idx]
        x_coords = [point[0] for point in bbox]
        y_coords = [point[1] for point in bbox]
        center_x = (min(x_coords) + max(x_coords)) / 2
        center_y = (min(y_coords) + max(y_coords)) / 2
        centers.append((int(center_x), int(center_y)))
    
    return centers

# 缩小图片
def resize_image(image_path, output_path, scale_factor=0.5):
    """
    压缩图片并保存缩小版本
    :param image_path: 原始图片路径
    :param output_path: 缩小图保存路径
    :param scale_factor: 缩放比例 (0-1)
    :return: (原始尺寸, 缩小图尺寸)
    """
    # 读取原始图像
    img = cv2.imread(image_path)
    if img is None:
        raise FileNotFoundError(f"图片不存在: {image_path}")
    
    # 获取原始尺寸
    orig_h, orig_w = img.shape[:2]
    
    # 计算新尺寸
    new_w = int(orig_w * scale_factor)
    new_h = int(orig_h * scale_factor)
    new_size = (new_w, new_h)
    
    # 使用INTER_AREA插值缩小图像（抗锯齿效果最佳）
    resized_img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
    
    # 保存缩小图
    cv2.imwrite(output_path, resized_img)
    return (orig_w, orig_h), (new_w, new_h)

# 将缩小图坐标还原到原始图像坐标系
def restore_coordinates(resized_coords, resized_size, original_size):
    """
    将缩小图坐标还原到原始图像坐标系
    :param resized_coords: 缩小图上的坐标 [x, y, w, h]
    :param resized_size: 缩小图尺寸 (w, h)
    :param original_size: 原始图尺寸 (w, h)
    :return: 原始图上的坐标 [x, y, w, h]
    """
    # 计算宽高缩放比例
    scale_x = original_size[0] / resized_size[0]
    scale_y = original_size[1] / resized_size[1]
    
    # 还原坐标
    orig_x = int(resized_coords[0] * scale_x)
    orig_y = int(resized_coords[1] * scale_y)
    orig_w = int(resized_coords[2] * scale_x)
    orig_h = int(resized_coords[3] * scale_y)
    
    return [orig_x, orig_y, orig_w, orig_h]






if __name__ == "__main__":
    # 1. 图片压缩 (缩放到50%)
    orig_size, resized_size = resize_image("cb5fdc20_screenshot.png", "resized.png", 0.3)
    print(f"原始尺寸: {orig_size}, 压缩后尺寸: {resized_size}")

    # 还原坐标到原始图像
    box = [100, 100, 100, 100]
    orig_box = restore_coordinates(box, resized_size, orig_size)
    x, y, w, h = orig_box
    print(f"原始图中的位置: X={x}, Y={y}, 宽度={w}, 高度={h}")